import cv2

# 加载人脸和眼睛的级联分类器
face_cascade = cv2.CascadeClassifier('D:\\OpenCV\\build\\etc\\haarcascades\\'
                                     'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('D:\\OpenCV\\build\\etc\\haarcascades\\'
                                    'haarcascade_eye.xml')

# 打开摄像头
cap = cv2.VideoCapture(0)

while True:
    # 读取摄像头帧
    ret, frame = cap.read()
    if not ret:
        break

    # 将帧转换为灰度图像
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 检测人脸
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
        # 在人脸周围绘制矩形框
        cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)

        # 获取人脸区域的灰度图像和彩色图像
        roi_gray = gray[y:y + h, x:x + w]
        roi_color = frame[y:y + h, x:x + w]

        # 在人脸区域内检测眼睛
        eyes = eye_cascade.detectMultiScale(roi_gray)
        for (ex, ey, ew, eh) in eyes:
            # 在眼睛周围绘制矩形框
            cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)

    # 显示处理后的帧
    cv2.imshow('Face Detection', frame)

    # 按下 'q' 键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头资源并关闭所有窗口
cap.release()
cv2.destroyAllWindows()